package com.ghostflying.wlanassistant;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.mobeta.android.dslv.DragSortController;
import com.mobeta.android.dslv.DragSortListView;

import android.support.v4.app.ListFragment;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;

public class WifiPriorityFragment extends ListFragment {

    ArrayAdapter<String> adapter;

    private ArrayList<String> list;
    private DragSortListView mDslv;
    private DragSortController mController;
    private Boolean isWifiOriginalEnabled = false;
    private WifiManager mWifiManager = null;
    private Boolean changeFlag = false;
    private storeToSupplicantThread mstoreToSupplicantThread;

    public int dragStartMode = DragSortController.ON_DOWN;
    public boolean removeEnabled = false;
    public int removeMode = DragSortController.FLING_REMOVE;
    public boolean sortEnabled = true;
    public boolean dragEnabled = true;
    

    private DragSortListView.DropListener onDrop =
            new DragSortListView.DropListener() {
                @Override
                public void drop(int from, int to) {
                    if (from != to) {
                        String item = adapter.getItem(from);
                        adapter.remove(item);
                        adapter.insert(item, to); 
                        if (!changeFlag){
                        	changeFlag = true;
                        }
                        //storeOrder();
                    }
                }
            };

    private DragSortListView.RemoveListener onRemove = 
            new DragSortListView.RemoveListener() {
                @Override
                public void remove(int which) {
                    adapter.remove(adapter.getItem(which));
                }
            };

    protected int getLayout() {
        // this DSLV xml declaration does not call for the use
        // of the default DragSortController; therefore,
        // DSLVFragment has a buildController() method.
        return R.layout.wifi_fragment_main;
    }
    
    /**
     * Return list item layout resource passed to the ArrayAdapter.
     */
    protected int getItemLayout() {
        /*if (removeMode == DragSortController.FLING_LEFT_REMOVE || removeMode == DragSortController.SLIDE_LEFT_REMOVE) {
            return R.layout.list_item_handle_right;
        } else */
/*    	if (removeMode == DragSortController.CLICK_REMOVE) {
            return R.layout.list_item_click_remove;
        } else {
            return R.layout.list_item_handle_left;
        }*/
    	return R.layout.list_item_bg_handle;
    }
    
    private void storeOrder (){
/*    	SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity());//getActivity().getPreferences(MainActivity.MODE_PRIVATE);
    	Editor editor = settings.edit();
    	editor.clear();
    	editor.putInt("total", adapter.getCount());
    	for (int i = 0;i < adapter.getCount();i++){    		
    		editor.putString(Integer.toString(i), adapter.getItem(i).replace("\"", ""));
    	}
    	editor.commit();
    	if (mstoreToSupplicantThread != null){
    		mstoreToSupplicantThread.interrupt();
    		mstoreToSupplicantThread = null;
    	}*/
    	mstoreToSupplicantThread = new storeToSupplicantThread();
    	mstoreToSupplicantThread.start();
    	//edit the supplicant priority

    }
    
    private class storeToSupplicantThread extends Thread {
    	
    	
    	@Override
    	public void run(){
    		if (!mWifiManager.isWifiEnabled()){
    			while (!mWifiManager.isWifiEnabled()){
        			mWifiManager.setWifiEnabled(true);
        			try {
    					Thread.sleep(100);
    				} catch (InterruptedException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
        		}  	
    			mWifiManager.disconnect();
    		}   		
    		List<WifiConfiguration> listStore = mWifiManager.getConfiguredNetworks();
        	for (WifiConfiguration r:listStore){
        		r.priority = 60 - 2*list.indexOf(r.SSID.replace("\"", ""));
        		mWifiManager.updateNetwork(r);
        	}    	
        	mWifiManager.saveConfiguration();
        	mWifiManager.setWifiEnabled(isWifiOriginalEnabled); 
    	}
    }
    
/*    private class StoreOrderTask extends AsyncTask<Void,Void,Void>{

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			storeOrder ();
			return null;
		}
    	
    }*/
    
/*    private ArrayList<String> getOrder(){   
    	ArrayList<String> result = new ArrayList<String>();
    	
    	SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity());
    	for (int i = 0; i < settings.getInt("total", 0); i++){
    		result.add(settings.getString(Integer.toString(i), "error"));
    	}
    	
    	
    	return result;
    }*/



    public DragSortController getController() {
        return mController;
    }

    /**
     * Called from DSLVFragment.onActivityCreated(). Override to
     * set a different adapter.
     */
    public void setListAdapter() {
/*        array = getResources().getStringArray(R.array.jazz_artist_names);
        list = new ArrayList<String>(Arrays.asList(array));

        adapter = new ArrayAdapter<String>(getActivity(), getItemLayout(), R.id.text, list);
        setListAdapter(adapter);*/
    	
/*        String[] array = getResources().getStringArray(R.array.jazz_artist_names);
        ArrayList<String> list = new ArrayList<String>(Arrays.asList(array));
        adapter = new MyAdapter(list);
        setListAdapter(adapter);*/
        GetWifiListTask mGetWifiListTask = new GetWifiListTask();
        mGetWifiListTask.execute();
        
    }

    /**
     * Called in onCreateView. Override this to provide a custom
     * DragSortController.
     */
    public DragSortController buildController(DragSortListView dslv) {
        // defaults are
        //   dragStartMode = onDown
        //   removeMode = flingRight
/*        DragSortController controller = new DragSortController(dslv);
        controller.setDragHandleId(R.id.drag_handle);
        controller.setClickRemoveId(R.id.click_remove);
        controller.setRemoveEnabled(removeEnabled);
        controller.setSortEnabled(sortEnabled);
        controller.setDragInitMode(dragStartMode);
        controller.setRemoveMode(removeMode);
        return controller;*/
        
        MyDSController c = new MyDSController(dslv);
        return c;
    }


    /** Called when the activity is first created. */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        mDslv = (DragSortListView) inflater.inflate(getLayout(), container, false);



        return mDslv;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mDslv = (DragSortListView) getListView(); 

        mDslv.setDropListener(onDrop);
        mDslv.setRemoveListener(onRemove);
        mController = buildController(mDslv);
        mDslv.setFloatViewManager(mController);
        mDslv.setOnTouchListener(mController);
        mDslv.setDragEnabled(dragEnabled);

       // Bundle args = getArguments();
/*        int headers = 0;
        int footers = 0;
        if (args != null) {
            headers = args.getInt("headers", 0);
            footers = args.getInt("footers", 0);
        }

        for (int i = 0; i < headers; i++) {
            addHeader(getActivity(), mDslv);
        }
        for (int i = 0; i < footers; i++) {
            addFooter(getActivity(), mDslv);
        }*/

        setListAdapter();
    }



/*    public static void addHeader(Activity activity, DragSortListView dslv) {
        LayoutInflater inflater = activity.getLayoutInflater();
        int count = dslv.getHeaderViewsCount();

        TextView header = (TextView) inflater.inflate(R.layout.header_footer, null);
        header.setText("Header #" + (count + 1));

        dslv.addHeaderView(header, null, false);
    }

    public static void addFooter(Activity activity, DragSortListView dslv) {
        LayoutInflater inflater = activity.getLayoutInflater();
        int count = dslv.getFooterViewsCount();

        TextView footer = (TextView) inflater.inflate(R.layout.header_footer, null);
        footer.setText("Footer #" + (count + 1));

        dslv.addFooterView(footer, null, false);
    }
    */
    private class MyAdapter extends ArrayAdapter<String> {
        
        public MyAdapter(List<String> artists) {
          super(getActivity(), getItemLayout(), R.id.text, artists);
        }

        public View getView(int position, View convertView, ViewGroup parent) {
          View v = super.getView(position, convertView, parent);
          v.getBackground().setLevel(3000);
          return v;
        }
      }
    
    private class MyDSController extends DragSortController {

        DragSortListView mDslv;

        public MyDSController(DragSortListView dslv) {
            super(dslv);
            setDragHandleId(R.id.text);
            mDslv = dslv;
        }

        @Override
        public View onCreateFloatView(int position) {
            View v = adapter.getView(position, null, mDslv);
            v.getBackground().setLevel(10000);
            return v;
        }

        @Override
        public void onDestroyFloatView(View floatView) {
            //do nothing; block super from crashing
        }

        @Override
        public int startDragPosition(MotionEvent ev) {
            int res = super.dragHandleHitPosition(ev);
            int width = mDslv.getWidth();

            if ((int) ev.getX() < width / 3) {
                return res;
            } else {
                return DragSortController.MISS;
            }
        }
    }
    
    private ArrayList<String> getWifiList(){
    	ArrayList<String> mlist = new ArrayList<String>();
    	mWifiManager = (WifiManager) getActivity().getSystemService(MainActivity.WIFI_SERVICE);
    	if (!mWifiManager.isWifiEnabled()){
    		while (mWifiManager.getWifiState() != WifiManager.WIFI_STATE_ENABLED){
    			mWifiManager.setWifiEnabled(true);
    			try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    		}
    		mWifiManager.disconnect();
    	}
    	else {
    		isWifiOriginalEnabled = true;
    	}
    	List<WifiConfiguration> wifiList = mWifiManager.getConfiguredNetworks();
    	
    	Comparator<WifiConfiguration> mComparator = new Comparator<WifiConfiguration>(){

			@Override
			public int compare(WifiConfiguration wifi0, WifiConfiguration wifi1) {
				// TODO Auto-generated method stub
				if (wifi0.priority != wifi1.priority){
					return wifi1.priority - wifi0.priority;
				}
				else{
					return 0;
				}				
			}
    		
    	};
    	
    	Collections.sort(wifiList,mComparator);
    	for(WifiConfiguration m:wifiList){
    		mlist.add(m.SSID.replace("\"", ""));
    	}
    	return mlist;
    }
    
    private class GetWifiListTask extends AsyncTask<Void, Void, ArrayList<String>>{
    	@Override
		protected void onPostExecute(ArrayList<String> result){
    		
/*			adapter = new MyAdapter (result);
			setListAdapter(adapter);
			adapter.notifyDataSetChanged();*/
    		list.clear();
    		for (String m:result){
    			list.add(m);
    		}
    		adapter.notifyDataSetChanged();    		
    		mWifiManager.setWifiEnabled(isWifiOriginalEnabled);    		
		}

		@Override
		protected ArrayList<String> doInBackground(Void... params) {
			// TODO Auto-generated method stub
			return getWifiList();
		}
		
		@Override
		protected void onPreExecute(){
			if (list == null){
				list = new ArrayList<String>();
				list.add("Wifi Information is loading.");
				list.add("Please wait for a moment.");
				adapter = new MyAdapter (list);
				setListAdapter(adapter);
			}			
		}    	
    }
    @Override  
    public void onDestroy() {
    	//storeOrder();
        super.onDestroy();  
    } 
    
    @Override
    public void onDestroyView(){
    	//storeOrder();
    	mDslv = null;
    	super.onDestroyView();
    }
    
/*    @Override
    public void setMenuVisibility(final boolean visible) {
        super.setMenuVisibility(visible);
        if ((!visible) && changeFlag) {
        	Log.d("fragment", "unvisible");
        	//storeOrder();
        }
    }*/
    @Override
    public void onPause(){
    	Log.d("fragment", "unvisible");
    	if (changeFlag){
    		storeOrder();
    		changeFlag = false;
    	}    	
    	super.onPause();    	
    }
}
